package com.culturalCenter.dataCenter.service.impl;

import com.culturalCenter.dataCenter.customEntity.CustomAdmin;
import com.culturalCenter.dataCenter.entity.JwtUser;
import com.culturalCenter.dataCenter.entity.user.Role;
import com.culturalCenter.dataCenter.entity.user.User;
import com.culturalCenter.dataCenter.entity.user.UserRole;
import com.culturalCenter.dataCenter.mapper.user.RoleMapper;
import com.culturalCenter.dataCenter.mapper.user.UserMapper;
import com.culturalCenter.dataCenter.mapper.user.UserRoleMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.List;

/**
 * 从数据库读取授权类型
 */
@Slf4j
public class UserDetailsServiceImpl implements UserDetailsService {

    @Resource
    private UserMapper adminMapper;
    @Resource
    private RoleMapper roleMapper;
    @Resource
    private UserRoleMapper adminRoleSiteMapper;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {

        List<Role> roles = new ArrayList<>();
        User admin = new User();
        admin.setNickName(s);
        List<User> users = (List<User>) adminMapper.queryAll(admin);
        if (users.size() > 0) {
            CustomAdmin user = new CustomAdmin(); // adminMapper.findUserByUserName(s);
            user.setUser(users.get(0));

            UserRole adminRoleSite = new UserRole();
            adminRoleSite.setUserId(user.getUser().getId());
            List<UserRole> adminRoleSites = (List<UserRole>) adminRoleSiteMapper.queryAll(adminRoleSite); // adminRoleSiteMapper.queryByIdAll(user.getAdmin().getId());
            for (UserRole as : adminRoleSites) {
                roles.add(roleMapper.queryById(as.getRoleId()));
            }
            user.setUserRoles(adminRoleSites);
            user.setRoles(roles);
            //            user.setRoles(Arrays.asList("ROLE_ADMIN", "ROLE_USER"));
            UserDetails userDetails = new JwtUser(user);
            //            List<GrantedAuthority> authorities = (List<GrantedAuthority>) userDetails.getAuthorities();
            return userDetails;
        } else {
            log.error("用户不存在");
            return null;
            //            throw new WrongUsernameException(AuthErrorEnum.LOGIN_NAME_ERROR.getMessage());
        }
    }

}
